<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/23 0023
 * Time: 14:59
 */
namespace app\modules\api\controllers;

use app\models\User;
use app\modules\api\models\PublishForm;
use app\hejiang\BaseApiResponse;
use app\models\Station;
use app\models\OrderRefund;
use app\models\Store;
use app\models\Order;
use app\behaviors\OrderBehavior;
use app\models\Shop;
use app\models\Mch;
use app\models\MchAccountLog;
use app\models\UserShareMoney;

class StationController extends Controller
{

    public $team_config = [
        ['day'=>30,'order_count'=>100, 'order_money'=>5000, 'money'=>388,],
        ['day'=>30,'order_count'=>300, 'order_money'=>15000, 'money'=>1288,],
        ['day'=>30,'order_count'=>500, 'order_money'=>25000, 'money'=>2588,]
    ];

    public $share_config = [
        ['term'=>1,'order_count'=>100, 'order_money'=>50, 'money'=>288,],
        ['term'=>1,'order_count'=>200, 'order_money'=>50, 'money'=>688,]
    ];

    //测试
    public function actionIndex()
    {

        //发放佣金
        $OrderBehavior = new OrderBehavior();
        $OrderBehavior->send_share_money(3,2706,2706,1,0);

        echo 1;exit;
//        $longitude = "111";
//        $latitude = "101";
//        $field = "id";
//        if($longitude && $latitude) {
//            $field .= ",( 3959 * acos ( cos ( radians({$latitude}) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians({$longitude}) ) + sin ( radians({$latitude}) ) * sin( radians( latitude ) ) )  )*1609.344 AS distance";
//            $order_by = "distance asc";
//        }
////        echo $field;exit;
//        $mch = Mch::find()->orderBy($order_by)->select($field)->asArray()->one();
////        echo "<pre>";print_r($mch);exit;
//        return new BaseApiResponse(['code'=>0,'msg'=>"操作成功",'data'=>$mch['id']]);
//

        $user_id= 3;

        $list = Station::find()->where([
            'user_id'=>$user_id,
            'is_delete' => 1,
        ])->orderBy('sort DESC')->all();
   
        if($list){
            return new BaseApiResponse(['code'=>0,'msg'=>"操作成功",'data'=>$list]);
        }else{
            return new BaseApiResponse(['code'=>1,'msg'=>"操作失败",'data'=>$list]);
        }

    }

    /**
     * 团长佣金和分销商的佣金
     */
    public function actionSendTeamMoney()
    {

        $time = time();
        $store = Store::findOne(2);
        $delivery_time = $time - ($store->delivery_time * 86400); //收货时间
        $sale_time = $time - ($store->after_sale_time * 86400); //售后时间


        //订单超过设置的确认收货时间，自动确认收货  商城
        $order_confirm = Order::find()->where([
            'is_delete' => 0, 'is_send' => 1, 'store_id' => 2, 'is_confirm' => 0,
        ])->andWhere(['<=', 'send_time', $delivery_time])->all();

        foreach ($order_confirm as $k => $v) {
            Order::updateAll(['is_confirm' => 1, 'confirm_time' => time()], ['id' => $v->id]);
            if($v->pay_type == 2){
                $v->is_pay = 1;
                $v->save();
            }
        }

        //超过设置的售后时间且没有在售后的订单--商城
        $order_list = Order::find()->alias('o')
            ->where([
                'and',
                ['o.is_delete' => 0, 'o.is_send' => 1, 'o.is_confirm' => 1, 'o.store_id' => 2, 'o.is_sale' => 0],
                ['<=', 'o.confirm_time', $sale_time],
            ])
            ->leftJoin(OrderRefund::tableName() . ' r', "r.order_id = o.id and r.is_delete = 0")
            ->select(['o.*'])->groupBy('o.id')
            ->andWhere([
                'or',
                'isnull(r.id)',
                ['r.type' => 2],
                ['in', 'r.status', [2, 3]]
            ])
            ->offset(0)->limit(20)->asArray()->all();

        foreach ($order_list as $index => $value) {
            Order::updateAll(['is_sale' => 1], ['id' => $value['id']]);

            if(!$value['shop_id'] && !$value['team_price']) continue;
            $shop = Shop::findOne($value['shop_id']);

            $OrderBehavior = new OrderBehavior();
            //发放分销商的佣金
            $OrderBehavior->send_share_money($value['team_price'],$shop->user_id,$value['id'],4,1);

            //发放团长佣金
            $OrderBehavior->share_money($value['id']);
        }

        return new BaseApiResponse(['code'=>0,'msg'=>"操作成功成功",'data'=>""]);

    }


    /**
     * 入驻商户订单金额转到商户余额
     * @param \yii\base\ActionEvent $e
     */
    public function actionTransferMch()
    {
        file_put_contents("/tmp/mch.log","start-".date("Y-m-d H:i:s").PHP_EOL,8);

        try {

            $order_list = Order::find()->where([
                'AND',
                ['is_pay' => 1],
                ['pay_type' => [1, 3]],
                ['is_sale' => 1],
                ['is_transfer' => 0],
                ['!=', 'mch_id', 0],
            ])->limit(50)->all();

            foreach ($order_list as $order) {
                $mch = Mch::findOne($order->mch_id);
                if (!$mch) continue;

                //商户金额结算
                $rate = 1 - $mch->transfer_rate/1000-$mch->service_rate/100;
                $account_money =  bcadd(0,$order->pay_price * $rate,2);
                file_put_contents("/tmp/mch.log",$rate."-".$order->pay_price."-".$account_money."-".PHP_EOL,8);

                $mch->account_money += $account_money;
                $mch->save();
                $order->is_transfer = 1;
                $order->save();

                $log = new MchAccountLog();
                $log->store_id = $order->store_id;
                $log->mch_id = $mch->id;
                $log->type = 1;
                $log->price = $account_money;
                $log->desc = '订单（' . $order->order_no . '）结算';
                $log->addtime = time();
                $log->save();
            }
        } catch (\Exception $e) {
            file_put_contents("/tmp/mch.log","error-".$e->getMessage().PHP_EOL,8);

        }

        return new BaseApiResponse(['code'=>0,'msg'=>"success",'data'=>""]);

    }


    /**
     * 团长奖励
     */
    public function actionTeamMoney()
    {
        $shop_list = Shop::find()->where(['is_default'=>1])->all();
        if(!$shop_list)   return new BaseApiResponse(['code'=>1,'msg'=>"无执行的数据",'data'=>""]);

        foreach ($shop_list as $shop) {

            $money = $this->getMoney($shop);
            if(!$money)  continue;
            $r = UserShareMoney::findOne(['user_id'=>$shop->user_id,'source'=>5]);
            if($r) continue;

            //发放佣金
            $OrderBehavior = new OrderBehavior();
            $OrderBehavior->send_share_money($money,$shop->user_id,$shop->id,5,1);
        }

        return new BaseApiResponse(['code'=>0,'msg'=>"success",'data'=>""]);

    }

    public function  getMoney($shop)
    {
        $start_time = $shop->addtime;
        $end_time = strtotime("+1month",$start_time);

        //订单的个数
        $order_count = Order::find()->where(['shop_id'=>$shop->id,'is_pay'=>1,'is_delete'=>0,'apply_delete'=>0,"is_cancel"=>0])
            ->andWhere(['>=',"pay_time",$start_time])->andWhere(['<=',"pay_time",$end_time])->count();


        //订单金额
        $order_money = Order::find()->where(['shop_id'=>$shop->id,'is_pay'=>1,'is_delete'=>0,'apply_delete'=>0,"is_cancel"=>0])
            ->andWhere(['>=',"pay_time",$start_time])->andWhere(['<=',"pay_time",$end_time])->sum("pay_price");

        $money = 0;
        foreach ($this->team_config as $k=>$config) {
            if($order_count>=$config['order_count'] && $order_money>=$config['order_money'])  $money=$config['money'];
        }

        return  $money;
    }

    /**
     * 分销商奖励 发放上一个月的
     */
    public function actionShareMoney()
    {

        $start_time= mktime(0,0,0,date('m'),1,date('Y'));
        $end_time = mktime(23,59,59,date('m'),date('t'),date('Y'));

        $user_list = User::find()->where(['is_distributor'=>1])->all();
        if(!$user_list)   return new BaseApiResponse(['code'=>1,'msg'=>"无执行的数据",'data'=>""]);

        foreach ($user_list as $user) {

            $money = $this->getShareMoney($user);
            if(!$money)  continue;
            $userShareMoney = UserShareMoney::find()->where(['user_id'=>$user->id,'source'=>6])->andWhere(['>=','addtime',$start_time])->andWhere(['<=','addtime',$end_time])->one();
            if($userShareMoney && $userShareMoney->addtime>=$start_time  &&  $userShareMoney->addtime<=$end_time ) continue;

            //发放佣金
            $OrderBehavior = new OrderBehavior();
            $OrderBehavior->send_share_money($money,$user->id,$user->id,6,0);
        }

        return new BaseApiResponse(['code'=>0,'msg'=>"success",'data'=>""]);

    }


    public function  getShareMoney($user)
    {
        $start_time= strtotime(date('Y-m-1',strtotime('last month')));
        $end_time = strtotime(date('Y-m-d',strtotime(date('Y-m-1').'-1 day')));
        $money = 0;
        foreach ($this->share_config as $k=>$config) {
            //订单的个数
            $order_count = Order::find()->where(['parent_id'=>$user->id,'is_pay'=>1,'is_delete'=>0,'apply_delete'=>0,"is_cancel"=>0])
                ->andWhere(['>=',"pay_time",$start_time])->andWhere(['<=',"pay_time",$end_time])->andWhere(['>=',"pay_price",$config['order_money']])->count();

            //订单金额
            $order_money = Order::find()->where(['parent_id'=>$user->id,'is_pay'=>1,'is_delete'=>0,'apply_delete'=>0,"is_cancel"=>0])
                ->andWhere(['>=',"pay_time",$start_time])->andWhere(['<=',"pay_time",$end_time])->andWhere(['>=',"pay_price",$config['order_money']])->sum("pay_price");

           if($order_count && $order_money )  $money = $config['money'];
        }

        return  $money;
    }

    /**
     *  秒杀未付款订单取消
     */
    public function  actionMsCancel()
    {
        //发放佣金
        $OrderBehavior = new OrderBehavior();
        $OrderBehavior->checkMsNoPayOrderTimeout();

    }




}
